package com.tacademy.lbs.server;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.http.*;

import com.tacademy.lbs.server.model.Place;

@SuppressWarnings("serial")
public class GetLocationListServlet extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		response.setHeader("Content-Encoding", "utf-8");
		response.setCharacterEncoding("utf-8");
		StringBuilder xmlStrBuilder = new StringBuilder();
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			StringBuilder query = new StringBuilder("select from ");
			query.append(Place.class.getName());
			query.append("  order by date desc");
			
			@SuppressWarnings("unchecked")
			List<Place> places = (List<Place>)pm.newQuery(query.toString()).execute();
			xmlStrBuilder.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
			xmlStrBuilder.append("<places>\n");
			for(Place place : places) {
				if (place.getLocation() == null) {
					place.setLocation("");
				}
				String[] locationArr = place.getLocation().split("@");
				String placeName = "";
				String coordinate = "";
				if (locationArr != null && locationArr.length == 2) {
					placeName = locationArr[0];
					coordinate = locationArr[1];
				}
				xmlStrBuilder.append("<place>\n");
				xmlStrBuilder.append("\t<key>").append(place.getKey()).append("</key>\n");
				xmlStrBuilder.append("\t<placeName>").append(placeName).append("</placeName>\n");
				xmlStrBuilder.append("\t<coordinate>").append(coordinate).append("</coordinate>\n");
				xmlStrBuilder.append("\t<id>").append(place.getId()).append("</id>\n");
				xmlStrBuilder.append("\t<date>").append(place.getDate()).append("</date>\n");
				xmlStrBuilder.append("\t<user>").append(place.getUser()).append("</user>\n");
				xmlStrBuilder.append("\t<count>").append(place.getCount()).append("</count>\n");
				xmlStrBuilder.append("</place>\n");
			}
			xmlStrBuilder.append("</places>\n");
			PrintWriter writer = response.getWriter();
			writer.write(xmlStrBuilder.toString());
			writer.flush();
		} finally {
			pm.close();
		}
	}
}
